#!/bin/bash

# ===============================================
# 脚本名称：setup_multi_ip.sh
# 脚本功能：一键配置 Debian 多IP绑定及策略路由
# 使用方法：sudo ./setup_multi_ip.sh
# 注意：请在使用前根据你的实际网络环境修改参数
# ===============================================

# 1. 配置参数
# 请根据你的实际情况修改以下变量
MAIN_IP="157.7.74.88"
NETMASK="255.255.254.0"
GATEWAY="157.7.74.1"
INTERFACE="eth1"
DNS="157.7.180.133 163.44.76.148"
TABLE_ID="200"
TABLE_NAME="extraip"
EXTRA_IPS=("157.7.74.89" "157.7.74.90" "157.7.74.91" "157.7.74.92" "157.7.74.93" "157.7.74.94" "157.7.74.95")

# 脚本文件路径
SETUP_SCRIPT="/usr/local/bin/setup_extraip.sh"
CLEAN_SCRIPT="/usr/local/bin/setup_extraip_clean.sh"

# 2. 创建路由表
echo ">>> 步骤 1: 创建路由表 ${TABLE_NAME}..."
if ! grep -q "${TABLE_ID} ${TABLE_NAME}" /etc/iproute2/rt_tables; then
    echo "${TABLE_ID} ${TABLE_NAME}" | sudo tee -a /etc/iproute2/rt_tables
    echo "路由表创建成功。"
else
    echo "路由表已存在，跳过。"
fi

# 3. 创建IP绑定及路由配置脚本
echo ">>> 步骤 2: 创建 IP 绑定和路由配置脚本..."
sudo tee ${SETUP_SCRIPT} > /dev/null <<EOF
#!/bin/bash
INTERFACE="${INTERFACE}"
GATEWAY="${GATEWAY}"
SUBNET="${SUBNET}"
TABLE_NAME="${TABLE_NAME}"
EXTRA_IPS=("${EXTRA_IPS[@]}")

for ip in "\${EXTRA_IPS[@]}"; do
  # 绑定IP地址
  ip addr add \${ip}/23 dev \${INTERFACE}

  # 添加路由规则
  ip rule add from \${ip}/32 table \${TABLE_NAME}
  ip route add ${MAIN_IP%/*}/23 dev \${INTERFACE} src \${ip} table \${TABLE_NAME}
  ip route add default via \${GATEWAY} dev \${INTERFACE} table \${TABLE_NAME}
done
EOF
echo "脚本 ${SETUP_SCRIPT} 创建成功。"

# 4. 创建清理脚本
echo ">>> 步骤 3: 创建清理脚本..."
sudo tee ${CLEAN_SCRIPT} > /dev/null <<EOF
#!/bin/bash
INTERFACE="${INTERFACE}"
TABLE_NAME="${TABLE_NAME}"
EXTRA_IPS=("${EXTRA_IPS[@]}")

for ip in "\${EXTRA_IPS[@]}"; do
  # 删除IP地址
  ip addr del \${ip}/23 dev \${INTERFACE}

  # 删除路由规则
  ip rule del from \${ip}/32 table \${TABLE_NAME}
done

# 清空整个路由表
ip route flush table \${TABLE_NAME}
EOF
echo "脚本 ${CLEAN_SCRIPT} 创建成功。"

# 5. 修改interfaces文件
echo ">>> 步骤 4: 配置 /etc/network/interfaces..."
sudo tee /etc/network/interfaces > /dev/null <<EOF
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# 主网卡配置
auto ${INTERFACE}
iface ${INTERFACE} inet static
    address ${MAIN_IP}
    netmask ${NETMASK}
    gateway ${GATEWAY}
    dns-nameservers ${DNS}
    
    # 在网卡启动后执行脚本来绑定额外的IP并配置路由
    post-up ${SETUP_SCRIPT}
    # 在网卡关闭前执行脚本来清理配置
    post-down ${CLEAN_SCRIPT}
EOF
echo "interfaces 文件配置完成。"

# 6. 赋予脚本执行权限
echo ">>> 步骤 5: 赋予脚本执行权限..."
sudo chmod +x ${SETUP_SCRIPT}
sudo chmod +x ${CLEAN_SCRIPT}
echo "权限设置完成。"

echo ">>> 脚本执行完毕。请重启服务器以应用所有配置。"
echo ">>> 执行命令: sudo reboot"